package com.clei.utils;

import java.util.Base64;

/**
 * Base64 util
 *
 * @author KIyA
 */
public class Base64Util {

    public static void main(String[] args) throws Exception {
        String base64Str = fileToBase64("D:\\Picture\\Mary\\Mary_0.png");
        base64ToFile(base64Str, "D:\\files\\xxx.pdf");
    }

    /**
     * encode
     *
     * @param bytes byte[]
     * @return String
     */
    public static String encode(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * decode
     *
     * @param str String
     * @return byte[]
     */
    public static byte[] decode(String str) {
        return Base64.getDecoder().decode(str);
    }

    /**
     * file -> base64字符串
     *
     * @param filePath 文件路径
     */
    public static String fileToBase64(String filePath) {
        byte[] bytes = FileUtil.toBytes(filePath);
        return encode(bytes);
    }

    /**
     * base64字符串 -> file
     *
     * @param str      base64字符串
     * @param filePath 输出文件路径
     */
    public static void base64ToFile(String str, String filePath) {
        byte[] bytes = decode(str);
        FileUtil.toFile(bytes, filePath);
    }
}
